package com.huanong.it.xwadmin.api;

import com.huanong.it.xwcommon.vo.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.huanong.it.xwcommon.entity.Admin;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("jwttoken");
        if (jwt == null || jwt.equals("")) {
            return true;//如果没有凭证，我必要解析，放过去下一个拦截器去自行判断要不要登录
        }
        Claims claims =null;
        try {
            claims = Jwts.parser().setSigningKey("111222").parseClaimsJws(jwt).getBody();
        }catch (ExpiredJwtException e){
            response.setStatus(401);
            response.getWriter().println("{\"code\":4001,\"data\":null,\"msg\":\"登录过期请重新登录\"}");
            return false;
        }catch (SignatureException e){
            response.setStatus(401);
            response.getWriter().println("{\"code\":4001,\"data\":null,\"msg\":\"登录凭证被篡改，请及时重新登录\"}");
            return false;
        }
        int id=Integer.parseInt(claims.get("admin_id").toString());
        String name=claims.get("admin_name").toString();
        String loginname=claims.get("admin_loginname").toString();
        int level=Integer.parseInt(claims.get("admin_level").toString());

        Admin admin=new Admin();
        admin.setId(id);
        admin.setName(name);
        admin.setLoginName(loginname);
        admin.setLevel(level);
        request.setAttribute("cur_admin",admin);//将用户信息放入request域中，后续controller可以直接获取
        return true;
    }
}
